package com.zimmur.quartz;

import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.zimmur.model.account.CouponDetail;
import com.zimmur.model.order.Order;
import com.zimmur.model.order.OrderDetail;
import com.zimmur.service.account.ICouponService;
import com.zimmur.service.goods.IGoodsSizeService;
import com.zimmur.service.order.IOrderDetailService;
import com.zimmur.service.order.IOrderService;
import com.zimmur.tools.DateUtils;

@Component
public class ProcessOrderTimeOut {
	private Logger log = LoggerFactory.getLogger(ProcessOrderTimeOut.class);
	
	@Resource
	private IOrderService orderService;
	@Resource
	private IOrderDetailService orderDetailService;
	@Resource
	private IGoodsSizeService goodsSizeService;
	@Resource
	private ICouponService couponService;
	/**
     * 每隔十分钟执行一次
     * @Scheduled(fixedRate = 10*60 * 1000) 
     */
	@Scheduled(fixedRate=10*60*1000)
	public void handlerOrder(){
		log.info("handlerOrder task begin");
		int dateTime = DateUtils.getNowUnixTime()-(24*60*60);
		List<Order> orders = orderService.selectListByTimeOut(dateTime);
		List<OrderDetail> orderDetails=null;
		for (Order order : orders) {
			try {
				orderDetails = orderDetailService.selectByOrderId(Long.parseLong(order.getOrderId()));
				if (!orderDetails.isEmpty()) {
					for (OrderDetail orderDetail : orderDetails) {
						if (orderDetail.getQuantity() > 0 ) {
							goodsSizeService.updateOccInventoryToInventory(Long.parseLong(orderDetail.getSizeCode()),
									orderDetail.getQuantity(),order.getOrderType());
						}
					}
					orderDetails.clear();
					orderService.updateOrderStatusToCancelByOrderId(Long.parseLong(order.getOrderId()));
				}
			} catch (Exception er) {
				log.error("update goodsSize error:"+er.getMessage(),er);
			}
			try {
				
				Short iscoupon=order.getIsusedCoupon();
				if(iscoupon!=null && iscoupon == 1){
					List<CouponDetail> couponDetails=couponService.selectCouponByOrderId(Long.parseLong(order.getOrderId()));
					
					if (couponDetails!=null) {
						for(CouponDetail couponDetail:couponDetails){
							couponDetail.setCouponState("2");
							couponService.updateCoupon(couponDetail);
							couponService.updateCouponStock(couponDetail.getCouponStockId(), 0, 0, -1);
						}
					}
				}
			} catch (Exception e) {
				log.error(e.getMessage(),e);
			}
			
		}
		orders.clear();
		log.info("handlerOrder task end");
	}
}
